package cli

import (
	"log"
	"net"
	"os"
	"time"

	"gitee.com/dark.H/go-remote-repl/lpc"
	"gitee.com/dark.H/go-remote-repl/remote"
	"github.com/Qingluan/Tunnel/tcp"
)

func StartOuterAPIServer(protocol ...string) {
	time.Sleep(1 * time.Second)
	var ln net.Listener
	var err error
	pro := "tls"

	if protocol != nil {
		pro = protocol[0]
		// ln, err = datas.UseDefaultTlsConfig("0.0.0.0:65531").WithTlsListener()
	}
	ln, err = tcp.ExpressListenWith("0.0.0.0:65531", pro, false)

	remote.DefaultHandleRecvJson = HandleJsonToAPIDB
	remote.DefaultGetAPINAMEs = lpc.GetAPINames
	remote.DefaultLPC = ClientLPC
	remote.DefaultRidEFunc = func(con net.Conn) {
		log.Println("ride to local sock file:", con.RemoteAddr())
		defer con.Close()
		if uco := lpc.SimpleClient(lpc.SOCK_FILE_PATH, protocol...); uco != nil {
			defer uco.Close()
			tcp.PipeFile(uco, con)
		}
	}

	if err == nil {
		if _, err = os.Stat(lpc.SOCK_FILE_PATH); err == nil {
			for {
				co, _ := ln.Accept()

				go func() {
					remote.NewApiServer(co)
				}()

			}
		} else {
			log.Fatal(err)
		}
	}
}
